import random

import numpy as np
from datetime import datetime, timedelta
from matplotlib import pyplot as plt
import matplotlib.dates as mdates

colors = {
    "0": (0, 100, 0),       # 深绿色
    "1": (0, 0, 255),       # 蓝色
    "2": (139, 0, 0),       # 深红色
    "3": (75, 0, 130),      # 深紫色
    "4": (139, 69, 19),     # 深棕色
    "11": (205, 133, 63),    # 深橙色
    "12": (0, 105, 105),     # 深青色
    "13": (139, 0, 139),     # 深洋红色
    "14": (40, 40, 40),      # 深灰色
    "15": (85, 107, 47),     # 深橄榄绿
    "16": (0, 105, 148),     # 深海蓝
    "21": (255, 0, 139),     # 深酒红
    "22": (85, 65, 0),       # 深咖啡色
    "23": (22, 55, 22),     # 深苔藓绿
    "24": (0, 0, 128),       # 深蓝色
    "25": (0, 206, 209),    # 青色
    "26": (102, 205, 170)   # Aquamarine
}


def get_hourly_indices(datetime_list):
    # 获取整点和整半小时的列表下标队列
    hourly_indices = []
    for index, dt in enumerate(datetime_list):
        if dt.minute == 0 and dt.second == 0:
            hourly_indices.append(index)
        elif dt.minute == 30 and dt.second == 0:
            hourly_indices.append(index)
    return hourly_indices


def show_pass_rate(DATA, TYPE=None, SHOW=False, SAVE=False, SAVE_PATH=None):
    # 提取数据
    times = list(DATA.keys())
    percentage = []
    for d in DATA.values():
        if TYPE is None:
            vaild_count = 0
            count = 0
            for k in d["type_pass_rate_dict"].keys():
                vaild_count += d["type_pass_rate_dict"][k]["vaild_count"]
                count += d["type_pass_rate_dict"][k]["count"]
            if count != 0:
                percentage.append(int(vaild_count / count * 100))
            else:
                percentage.append(None)
        else:
            if TYPE in d["type_pass_rate_dict"].keys():
                perce = d["type_pass_rate_dict"][TYPE]["vaild_count"] / d["type_pass_rate_dict"][TYPE]["count"]
                percentage.append(int(perce * 100))
            else:
                percentage.append(None)
    # 第一组
    plt.plot(times, percentage, marker='o', linestyle='-', color='r', label='通过率')
    # 绘制70分位数线
    plt.axhline(y=70, color='b', linestyle='--', label='70% Line')

    # 设置X轴为每1小时一个标记
    ax = plt.gca()  # 获取当前的Axes
    fig = ax.figure
    fig.set_size_inches(20, 10)  # 宽度为10英寸，高度为6英寸
    # # ax.xaxis.set_major_locator(mdates.HourLocator(interval=1))  # 每1小时一个主要刻度
    # # ax.xaxis.set_major_locator(mdates.MinuteLocator(byminute=[0, 10]))  # 每半小时一个主要刻度
    # ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))  # 设置时间格式
    # plt.gcf().autofmt_xdate()  # 自动调整X轴日期标签的格式
    hours = mdates.HourLocator(interval=1)  # 每1小时一个刻度
    ax.xaxis.set_major_locator(hours)
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
    plt.xticks(rotation=45)  # 将X轴标签旋转45度

    # 添加标签和标题
    ax.set_xlabel('时间')
    ax.set_ylabel('通过率（%）')
    ax.set_title('通过率')
    ax.legend(loc='upper right')


    if SHOW:
        # 显示图表
        plt.show()
    if SAVE:
        # 保存图表
        if SAVE_PATH is not None:
            plt.savefig(SAVE_PATH)
        plt.close()


def show_speed(DATA, TYPE=None, SHOW=False, SAVE=False, SAVE_PATH=None):
    # 提取数据
    times = list(DATA.keys())
    mean_speed = []
    for d in DATA.values():
        if d["type_speed_dict"]:
            if TYPE is None:
                all_speed = 0
                count = 0
                for k in d["type_speed_dict"].keys():
                    all_speed += d["type_speed_dict"][k]["mean_speed"] * d["type_speed_dict"][k]["count"]
                    count += d["type_speed_dict"][k]["count"]
                mean_speed.append(round((all_speed/count), 2))
            else:
                if TYPE in d["type_speed_dict"].keys():
                    mean_speed.append(d["type_speed_dict"][TYPE]["mean_speed"])
        else:
            mean_speed.append(None)

    plt.plot(times, mean_speed, marker='o', linestyle='-', color='r', label='速度')

    # 设置X轴为每1小时一个标记
    ax = plt.gca()  # 获取当前的Axes
    fig = ax.figure
    fig.set_size_inches(20, 10)  # 宽度为10英寸，高度为6英寸
    # ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))  # 设置时间格式
    # plt.gcf().autofmt_xdate()  # 自动调整X轴日期标签的格式
    hours = mdates.HourLocator(interval=1)  # 每1小时一个刻度
    ax.xaxis.set_major_locator(hours)
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
    plt.xticks(rotation=45)  # 将X轴标签旋转45度
    # 添加标签和标题
    ax.set_xlabel('时间')
    ax.set_ylabel('速度(km/h)')
    ax.set_title('速度变化曲线')
    ax.legend(loc='upper right')

    if SHOW:
        # 显示图表
        plt.show()
    if SAVE:
        # 保存图表
        if SAVE_PATH is not None:
            plt.savefig(SAVE_PATH)
        plt.close()


def show_slow_num(DATA, TYPE=None, SHOW=False, SAVE=False, SAVE_PATH=None):
    # 提取数据
    times = list(DATA.keys())
    slow_num = []
    for d in DATA.values():
        if d["type_speed_dict"]:
            if TYPE is None:
                count = 0
                for k in d["type_speed_dict"].keys():
                    count += d["type_speed_dict"][k]["slow_level_count"]
                slow_num.append(count)
            else:
                if TYPE in d["type_speed_dict"].keys():
                    slow_num.append(d["type_speed_dict"][TYPE]["slow_level_count"])
        else:
            slow_num.append(None)

    plt.plot(times, slow_num, marker='o', linestyle='-', color='r', label='慢行车数量')

    # 设置X轴为每1小时一个标记
    ax = plt.gca()  # 获取当前的Axes
    fig = ax.figure
    fig.set_size_inches(20, 10)  # 宽度为10英寸，高度为6英寸
    # ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))  # 设置时间格式
    # plt.gcf().autofmt_xdate()  # 自动调整X轴日期标签的格式
    hours = mdates.HourLocator(interval=1)  # 每1小时一个刻度
    ax.xaxis.set_major_locator(hours)
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
    plt.xticks(rotation=45)  # 将X轴标签旋转45度
    # 添加标签和标题
    ax.set_xlabel('时间')
    ax.set_ylabel('慢行车数量(辆)')
    ax.set_title('慢行车数量变化曲线')
    ax.legend(loc='upper right')

    if SHOW:
        # 显示图表
        plt.show()
    if SAVE:
        # 保存图表
        if SAVE_PATH is not None:
            plt.savefig(SAVE_PATH)
        plt.close()


def show_flow(DATA, SHOW=False, SAVE=False, SAVE_PATH=None):
    # 提取数据
    times = sorted(DATA.keys())  # 对时间点进行排序
    time_labels = [timee.strftime('%H:%M') for timee in times]
    index = np.arange(len(times))
    # 设置柱状图的宽度
    # bar_width = 0.35
    up_flow = []
    down_flow = []
    # total = []
    for d in DATA.values():
        up_flow.append(d["up_flow_num"])
        down_flow.append(d["down_flow_num"])
        # total.append(d["total_match"])

    # plt.bar(index, up_flow, width=bar_width, label='上游流量')
    # plt.bar(index + bar_width, down_flow, width=bar_width, label='下游流量')
    # plt.plot(index + bar_width, total, marker='o', markersize=1, linestyle='-', color='k', label='匹配数量')

    # # 设置 x 轴的刻度和标签
    # hourly_indices = get_hourly_indices(times)
    # ticks = [index[i] + bar_width / 2 for i in hourly_indices]  # 每隔12个索引选取一个
    # tick_labels = [time_labels[i] for i in hourly_indices]  # 对应的标签也每隔12个选取一个
    #
    # # 设置X轴为每1小时一个标记
    # ax = plt.gca()
    # fig = ax.figure
    # fig.set_size_inches(20, 10)
    # ax.set_xticks(ticks, tick_labels, rotation=45)

    plt.plot(times, up_flow, linestyle='-', color='b', label='上游流量')
    plt.plot(times, down_flow, linestyle='-', color='r', label='下游流量')

    # 设置X轴为每1小时一个标记
    ax = plt.gca()  # 获取当前的Axes
    fig = ax.figure
    fig.set_size_inches(20, 10)  # 宽度为10英寸，高度为6英寸
    # ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))  # 设置时间格式
    # plt.gcf().autofmt_xdate()  # 自动调整X轴日期标签的格式
    hours = mdates.HourLocator(interval=1)  # 每1小时一个刻度
    ax.xaxis.set_major_locator(hours)
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
    plt.xticks(rotation=45)  # 将X轴标签旋转45度

    # 添加标签和标题
    ax.set_xlabel('时间')
    ax.set_ylabel('流量(辆)')
    ax.set_title('流量变化曲线')
    ax.legend(loc='upper right')

    if SHOW:
        # 显示图表
        plt.show()
    if SAVE:
        # 保存图表
        if SAVE_PATH is not None:
            plt.savefig(SAVE_PATH)
        plt.close()


def show_match(DATA, SHOW=False, SAVE=False, SAVE_PATH=None):
    # 提取数据
    times = sorted(DATA.keys())  # 对时间点进行排序
    total = []
    for d in DATA.values():
        total.append(d["total_match"])

    plt.plot(times, total, marker='o', markersize=1, linestyle='-', color='k', label='匹配数量')

    # 设置X轴为每1小时一个标记
    ax = plt.gca()  # 获取当前的Axes
    fig = ax.figure
    fig.set_size_inches(20, 10)  # 宽度为10英寸，高度为6英寸
    # ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))  # 设置时间格式
    # plt.gcf().autofmt_xdate()  # 自动调整X轴日期标签的格式
    hours = mdates.HourLocator(interval=1)  # 每1小时一个刻度
    ax.xaxis.set_major_locator(hours)
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
    plt.xticks(rotation=45)  # 将X轴标签旋转45度

    # 添加标签和标题
    ax.set_xlabel('时间')
    ax.set_ylabel('匹配数量(辆)')
    ax.set_title('匹配数量变化曲线')
    ax.legend(loc='upper right')

    if SHOW:
        # 显示图表
        plt.show()
    if SAVE:
        # 保存图表
        if SAVE_PATH is not None:
            plt.savefig(SAVE_PATH)
        plt.close()


def show_time_duration(DATA, TYPE=None, SHOW=False, SAVE=False, SAVE_PATH=None):
    # 提取数据
    times = list(DATA.keys())
    time_duration = {}
    k_keys = [k for k in colors.keys()]
    for k in k_keys:
        time_duration[k] = []
    for d in DATA.values():
        if d["type_pass_rate_dict"]:
            for k in k_keys:
                if k in d["type_pass_rate_dict"].keys():
                    duration = sum(d["type_pass_rate_dict"][k]["value"])
                    count = d["type_pass_rate_dict"][k]["count"]
                    time_duration[k].append(round((duration / count), 2))
                else:
                    time_duration[k].append(None)
        else:
            for k in k_keys:
                time_duration[k].append(None)
    if TYPE is None:
        for k in k_keys:
            all_none = all(x is None for x in time_duration[k])
            if not all_none:
                plt.scatter(times, time_duration[k], color=[c / 255 for c in colors[k]], label='车型：' + k)
    else:
        if TYPE in k_keys:
            plt.scatter(times, time_duration[TYPE], color=[c / 255 for c in colors[TYPE]], label='车型：' + TYPE)
        else:
            print("不存在车型：" + TYPE)

    # 设置X轴为每1小时一个标记
    ax = plt.gca()  # 获取当前的Axes
    fig = ax.figure
    fig.set_size_inches(20, 10)  # 宽度为10英寸，高度为6英寸
    # ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))  # 设置时间格式
    # plt.gcf().autofmt_xdate()  # 自动调整X轴日期标签的格式
    hours = mdates.HourLocator(interval=1)  # 每1小时一个刻度
    ax.xaxis.set_major_locator(hours)
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
    plt.xticks(rotation=45)  # 将X轴标签旋转45度
    # 添加标签和标题
    ax.set_xlabel('时间')
    ax.set_ylabel('通行时间(分钟)')
    ax.set_title('通行时间变化曲线')
    ax.legend(loc='upper right')

    if SHOW:
        # 显示图表
        plt.show()
    if SAVE:
        # 保存图表
        if SAVE_PATH is not None:
            plt.savefig(SAVE_PATH)
        plt.close()


if __name__ == '__main__':
    print("1111111111111")
    time1 = datetime(2024, 1, 1, 0, 00, 00)
    n = 24
    timee = [time1 + timedelta(minutes=i) for i in range(n)]
    up_list = [random.randint(1, 100) for _ in range(n)]
    down_list = [random.randint(1, 100) for _ in range(n)]
    data = {}
    for i in range(n):
        data[timee[i]] = {"up_flow_num": up_list[i], "down_flow_num": down_list[i], "total_match": 30}

    show_flow(data, SHOW=True, SAVE=False, SAVE_PATH=None)
